package com.moteur.analysersite.builtwith;

import java.io.IOException;
import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.moteur.analysersite.util.TimeOut;

import com.moteur.analysersite.exceptionPersonnaliser.UrlException;


public class SiteWebTechnologiesBuiltWith {

	// exemple url "exemple.com"
	private String url;
	private String cssPath;
	private Document doc;
	private TimeOut timeOutSecond;
	private ArrayList<TechnologieBW> technologieSite;

	public SiteWebTechnologiesBuiltWith() {
		super();
		this.cssPath = "div.span8 div";
		technologieSite = new ArrayList<TechnologieBW>();
		this.timeOutSecond = TimeOut.getInstance();
	}

	public SiteWebTechnologiesBuiltWith(String url) {
		super();
		this.url = url;
		this.cssPath = "div.span8 div";
		technologieSite = new ArrayList<TechnologieBW>();
		this.timeOutSecond = TimeOut.getInstance();
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getCssPath() {
		return cssPath;
	}

	public void setCssPath(String cssPath) {
		this.cssPath = cssPath;
	}

	public TimeOut getTimeOutSecond() {
		return timeOutSecond;
	}

	public void setTimeOutSecond(TimeOut timeOutSecond) {
		this.timeOutSecond = timeOutSecond;
	}

	public ArrayList<TechnologieBW> analyser() throws UrlException {
		if (url == null) {
			throw new UrlException();
		}
		try {
			// le site a parser
			doc = Jsoup.connect("http://builtwith.com/" + url)
					.timeout(timeOutSecond.getTimeout() * 1000).get();
			// Le selecteur CSS
			Elements contents = doc.select(cssPath);
			// Objet Technologie qui contient Categorie + list des technologies
			// de cette Categorie
			TechnologieBW technologie = new TechnologieBW();
			boolean entrer = false;
			for (Element content : contents) {
				if (content.attr("class").equals("titleBox")) {
					if (entrer) {
						this.technologieSite.add(new TechnologieBW(technologie
								.getCategorie(), technologie.getTechnologie()));
						technologie.setTechnologie(new ArrayList<String>());
					}
					entrer = true;
					technologie.setCategorie(content.child(0).child(0).text());
				}
				if (content.attr("class").equals("techItem")) {
					technologie.ajouterTechno(content.child(0).text());
				}
			}
			this.technologieSite.add(new TechnologieBW(
					technologie.getCategorie(), technologie.getTechnologie()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return this.technologieSite;
	}
}
